package com.hrm.common.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 配置feign拦截器，解决调用其他服务时请求头无sessionid信息的问题
 */
@Configuration
public class FeignConfiguration {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            //获取浏览器发送的请求属性，把请求头输入feign
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //RequestContextHolder获取请求属性
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest(); //获取请求对象
                    Enumeration<String> headerNames = request.getHeaderNames(); //获取请求头名称集合
                    if (headerNames != null) {
                        while (headerNames.hasMoreElements()) {
                            String headerName = headerNames.nextElement();
                            String value = request.getHeader(headerName); //获取请求头的值
                            requestTemplate.header(headerName, value); //请求头加入到feign请求模板中，这样调用的服务会接收到与当前服务一样的请求头
                        }
                    }
                }
            }
        };
    }
}
